<template>
	<view class="content">
		<view class="bgColor">
			<image src="/static/home/cultivateBg.png" mode=""></image>
		</view>
		<cusHeaderVue titleContent="培训中心" :showBack="true"></cusHeaderVue>
		<scroll-view scroll-y="true"
			:style="{paddingTop: `calc(${scrollerHeight} + 90rpx)`,height: `calc(100vh - ${scrollerHeight} - 90rpx)`}">
			<view class="contBox">
				<view class="contTop">
					<view class="contTopTop">
						<!-- <view class="contTag">
							门店宣讲
						</view> -->
						<view class="contTag contTagA">
							{{ vm.tag }}
						</view>
						<view class="contName">
							{{ vm.title || '—' }}
						</view>
					</view>
					<view class="contText">
						<view class="contTextName">
							培训简介
						</view>
						<view class="contTextCont">
							{{ vm.description || '—' }}
						</view>
					</view>
					<view class="contBottom">
						<view class="contTime">
							{{ vm.trainingTime || '' }}
						</view>

					</view>

				</view>
				<view class="contWork">
					<view class="contWorkTit">
						作业详情（{{ vm.submitNick || '—' }}）
					</view>
					<view class="contWorkBox">
						<view class="contWorkLi">
							<view class="contWorkName">
								提交时间
							</view>
							<view class="contWorkText">
								{{ vm.submitTime || '' }}
							</view>
						</view>
						<view class="contWorkLi">
							<view class="contWorkName">
								培训结果
							</view>
							<view class="contWorkText">
								{{ vm.content || '' }}
							</view>
						</view>
						<view class="contWorkLi" v-if="vm.imageUrls.length || vm.videoUrls.length">
							<view class="contWorkName">
								照片/视频
						</view>
							<view class="contWorkImg">
								<view class="contWorkImgLi" v-for="(img, idx) in vm.imageUrls" :key="'img'+idx" @click="onImageClick(idx)">
									<image :src="img" mode="aspectFill"></image>
								</view>
								<view class="contWorkImgLi videoWrap" v-for="(vid, idx) in vm.videoUrls" :key="'vid'+idx">
									<video controls :src="vid"></video>
									<view class="videoMask" @click.stop="onVideoClick(vid)"></view>
								</view>
							</view>
						</view>
					</view>
					<view class="contFj" v-if="vm.courseFiles.length || vm.submitFile">
						<image src="/static/home/fujian.png" mode=""></image>
						附件：
						<text v-for="(u, i) in vm.courseFiles" :key="'cf'+i" class="fileLink" @click="onFileClick(u)">《{{ fileName(u) }}》<text v-if="i < vm.courseFiles.length - 1">、</text></text>
						<text v-if="vm.courseFiles.length && vm.submitFile">、</text>
						<text v-if="vm.submitFile" class="fileLink" @click="onFileClick(vm.submitFile)">《{{ fileName(vm.submitFile) }}》</text>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script setup>
	import {
		onLoad,
	} from '@dcloudio/uni-app';
	import {
		ref, computed
	} from 'vue';
	import cusHeaderVue from '@/components/cus-header.vue';
	import { GETTrainingSubmitDetail } from '@/api/interface.js';
	import { formatDateTime } from '@/utils/date.js';

	// 作业提交详情
	const submitDetail = ref(null);
	const pageId = ref('');
	const scrollerHeight = ref('');

	// 简单清洗 API 返回的 URL（去掉反引号和首尾空格）
	const cleanUrl = (val) => {
		if (!val) return '';
		return String(val).replace(/[`]/g, '').trim();
	};
	const fileName = (url) => {
		if (!url) return '';
		try {
			const u = cleanUrl(url).split('?')[0];
			return decodeURIComponent(u.substring(u.lastIndexOf('/') + 1));
		} catch(e) {
			return '';
		}
	};

	const vm = computed(() => {
		const d = submitDetail.value || {};
		const c = d.dxCurses || {};
		const tag = (c.cursesType === '2' || c.cursesType === 2) ? '课件学习' : '门店宣讲';
		const title = c.title || '';
		const description = c.description || '';
		const trainingTime = c.createTime ? formatDateTime(c.createTime) : '';
		const submitNick = d.nickname || '';
		const submitTime = d.createTime ? formatDateTime(d.createTime) : '';
		const content = d.content || '';

		const imageUrls = [];
		if (d.imageUrl) {
			const raw = String(d.imageUrl);
			raw.split(',').map(s => cleanUrl(s)).forEach(u => { if (u) imageUrls.push(u) });
		}
		const videoUrls = [];
		if (d.videoUrl) {
			const raw = String(d.videoUrl);
			raw.split(',').map(s => cleanUrl(s)).forEach(u => { if (u) videoUrls.push(u) });
		}
		const submitFile = d.fileUrl ? cleanUrl(d.fileUrl) : '';
		const courseFiles = Array.isArray(c.fileUrl) ? c.fileUrl.map(cleanUrl).filter(Boolean) : [];

		return { tag, title, description, trainingTime, submitNick, submitTime, content, imageUrls, videoUrls, submitFile, courseFiles };
	});

	//获取状态栏高度
	const getBarHeight = () => {
		uni.getSystemInfo({
			success: function(res) {
				scrollerHeight.value = res.statusBarHeight + 'px'
			}
		});
	}

	// 拉取作业提交详情
	const fetchSubmitDetail = async (id) => {
		try {
			const res = await GETTrainingSubmitDetail({ id });
			if (res && res.code === 0) {
				submitDetail.value = res.data || null;
				console.log('作业提交详情', submitDetail.value);
			} else {
				console.warn('获取作业详情失败', res?.message || res);
			}
		} catch (e) {
			console.error('获取作业详情异常', e);
		}
	}

	const toUrl = (urlSrc) => {
		uni.navigateTo({
			url: urlSrc
		})
	}

	// 预览图片
	const onImageClick = (idx) => {
		const urls = vm.value.imageUrls || [];
		if (!urls.length) return;
		uni.previewImage({
			current: idx,
			urls
		});
	};

	// 全屏播放视频（跳转到公共播放器）
	const onVideoClick = (src) => {
		const url = cleanUrl(src);
		if (!url) return;
		uni.navigateTo({
			url: `/pages/common/videoPlayer?src=${encodeURIComponent(url)}`
		});
	};

	// 打开附件（H5 直接新开，非 H5 下载后用 openDocument 打开）
	const onFileClick = (src) => {
		const url = cleanUrl(src);
		if (!url) return;
		// #ifdef H5
		window.open(url, '_blank');
		// #endif
		// #ifndef H5
		uni.showLoading({ title: '正在打开...' });
		uni.downloadFile({
			url,
			success: (res) => {
				const filePath = res.tempFilePath;
				uni.openDocument({
					filePath,
					showMenu: true,
					success: () => {},
					fail: (e) => {
						console.error('打开附件失败', e);
						uni.showToast({ title: '无法打开附件', icon: 'none' });
					}
				});
			},
			fail: (err) => {
				console.error('附件下载失败', err);
				uni.showToast({ title: '附件下载失败', icon: 'none' });
			},
			complete: () => {
				uni.hideLoading();
			}
		});
		// #endif
	};

	onLoad((options) => {
		getBarHeight();
		// 从路由参数获取 id，例如：.../homeworkDetails?id=124
		const id = options?.id || '';
		pageId.value = id;
		if (id) {
			fetchSubmitDetail(String(id));
		} else {
			console.warn('未传入作业提交ID');
		}
	})
</script>

<style lang="scss" scoped>
	.content {
		width: 100%;
		height: 100vh;
	}

	.bgColor {
		width: 100%;
		height: 740rpx;
		position: absolute;
		z-index: -1;
		top: 0;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.contBox {
		padding: 22rpx;
		box-sizing: border-box;
		padding-bottom: calc(env(safe-area-inset-bottom) + 101rpx);

		.contTop {
			width: 100%;
			border-radius: 12.82rpx 12.82rpx 0 0;
			background: #ffffff;
			box-shadow: 2.56rpx 4.49rpx 10.9rpx 0.64rpx #c0c0c03b;
			padding: 33rpx 25rpx;
			box-sizing: border-box;

			.contTopTop {
				display: flex;
				align-items: center;

				.contTag {
					width: 113.46rpx;
					height: 38.46rpx;
					border-radius: 6.41rpx 6.41rpx 6.41rpx 6.41rpx;
					background: linear-gradient(-90deg, #83acfa, #91d0fe);
					box-shadow: 2.56rpx 4.49rpx 10.9rpx 0.64rpx #83adfa3b;
					font-weight: 500;
					font-size: 23.08rpx;
					color: #FFFFFF;
					display: flex;
					align-items: center;
					justify-content: center;
				}

				.contTagA {
					background: linear-gradient(-90deg, #ff7b44, #fe9d35);
					box-shadow: 2.56rpx 4.49rpx 10.9rpx 0.64rpx #ff7c433b;
				}

				.contName {
					font-weight: 500;
					font-size: 32.05rpx;
					color: #1C2027;
					margin-left: 12rpx;
				}
			}

			.contText {
				margin-top: 26rpx;
				border-radius: 12.82rpx 12.82rpx 12.82rpx 12.82rpx;
				background: #f4f6f9;
				width: 100%;
				padding: 26rpx 24rpx;
				box-sizing: border-box;
				display: flex;

				.contTextName {
					font-size: 24.36rpx;
					font-weight: 400;
					color: #7F8494;
				}

				.contTextCont {
					color: #222222;
					font-weight: 400;
					font-size: 24.36rpx;
					margin-left: 13rpx;
					flex: 1;
				}
			}

			.contBottom {
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-top: 27rpx;

				.contTime {
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
					font-size: 23.08rpx;
					font-weight: 400;
					color: #7F8494;
				}

				
			}

		}

		.contWork {
			padding: 47rpx 25rpx;
			box-sizing: border-box;
			background: #ffffff;
			border-top: 1px solid #D7D7D7;
			.contWorkTit{
				font-weight: 500;
				font-size: 32.05rpx;
				color: #1C2027;
			}
			.contWorkBox{
				width: 100%;
				border-radius: 12.82rpx 12.82rpx 12.82rpx 12.82rpx;
				background: #f4f6f9;
				padding: 35rpx 23rpx 2rpx;
				box-sizing: border-box;
				margin-top: 26rpx;
				
				.contWorkLi{
					display: flex;
					margin-bottom: 35rpx;
					.contWorkName{
						font-size: 24.36rpx;
						font-weight: 400;
						color: #7F8494;
						width: 120rpx;
						text-align: right;
						margin-right: 15rpx;
					}
					.contWorkText{
						font-size: 24.36rpx;
						font-weight: 400;
						color: #222222;
						flex: 1;
					}
					.contWorkImg{
						display: grid;
						grid-template-columns: repeat(2, 1fr); /* 六列，每列占 1 份 */
						  gap: 25rpx; /* 可选：列之间的间距 */
						.contWorkImgLi{
							width: 170rpx;
							height: 125rpx;
							image{
								width: 100%;
								height: 100%;
							}
							video{
								width: 100%;
								height: 100%;
							}
						}
						.videoWrap{
							position: relative;
						}
						.videoMask{
							position: absolute;left:0;top:0;right:0;bottom:0;z-index:2;
						}
					}
				}
			}
			.contFj {
				font-size: 23.08rpx;
				font-weight: 400;
				color: #4580F6;
				margin-top: 25rpx;
				.fileLink{ text-decoration: underline; }
				image {
					width: 17.95rpx;
					height: 20.51rpx;
				}
			}
		}


	}
</style>